<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div>
    <div v-loading="loading">
      <div style="padding: 10px">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="公制（毫米-牛顿）" name="first">
            <div v-if="activeName === 'first'" class="mainStyle">
              <div class="treeDiv" :style="{ width: leftWidth - 0.3 + '%' }">
                <el-input
                  v-model="queryName"
                  placeholder="请输排号或板材代号"
                  prefix-icon="Search"
                  clearable
                  style="margin-bottom: 10px"
                  @clear="clearQuery"
                />
                <el-tree
                  ref="materialTree"
                  :data="treeData"
                  node-key="_id"
                  highlight-current
                  :default-expand-all="true"
                  :props="defaultProps"
                  :filter-node-method="filterNode"
                  icon-class="el-icon-arrow-right"
                  :expand-on-click-node="false"
                  @node-click="customTreeClick"
                >
                  <template #default="slotProps">
                    <span v-html="highlightLabel(slotProps.data.nodeName)"></span>
                  </template>
                </el-tree>
              </div>
              <div class="resizer" @mousedown.prevent="startResize"></div>
              <div class="rightDiv" :style="{ width: 100 - leftWidth + '%' }">
                <bord
                  v-if="activeName === 'first'"
                  :active-name="activeName"
                  :select-tree-node-id="selectTreeNodeId"
                  :fastener-grade="fastenerGrade"
                />
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="英制（英寸-磅）" name="second">
            <div v-if="activeName === 'second'" class="mainStyle">
              <div class="treeDiv" :style="{ width: leftWidth - 0.3 + '%' }">
                <el-input
                  v-model="queryName"
                  placeholder="请输排号或板材代号"
                  prefix-icon="Search"
                  clearable
                  style="margin-bottom: 10px"
                  @clear="clearQuery"
                />
                <el-tree
                  ref="materialTree"
                  :data="treeData"
                  node-key="_id"
                  highlight-current
                  :default-expand-all="true"
                  :props="defaultProps"
                  :filter-node-method="filterNode"
                  icon-class="el-icon-arrow-right"
                  :expand-on-click-node="false"
                  @node-click="customTreeClick"
                >
                  <template #default="slotProps">
                    <span v-html="highlightLabel(slotProps.data.nodeName)"></span>
                  </template>
                </el-tree>
              </div>
              <div class="resizer" @mousedown.prevent="startResize"></div>
              <div class="rightDiv" :style="{ width: 100 - leftWidth + '%' }">
                <bord
                  v-if="activeName === 'second'"
                  :active-name="activeName"
                  :select-tree-node-id="selectTreeNodeId"
                  :fastener-grade="fastenerGrade"
                />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
        <!-- <el-button type="primary" size="small" style="position: absolute; top: 28px; right: 30px" @click="handleUpload">导入数据</el-button> -->
      </div>
    </div>
    <importDialog v-if="importVisible" :import-visible="importVisible" @handle-event="handleImportEvent" />
  </div>
</template>
<script setup>
import { getFastenerTree } from '@/api/fastenerData';
import bord from './components/bord.vue';
import importDialog from './components/importDialog.vue';
const importVisible = ref(false);
//左侧数结构
const loading = ref(true);
const treeData = ref([]);
const leftWidth = ref(20);
const materialTree = ref();
const queryName = ref('');
const defaultProps = { children: 'children', label: 'nodeName' };
//树选择节点
const selectTreeNodeId = ref('');
const fastenerGrade = ref('');
const currentNodeKey = ref(null);
//右侧tab切换
const activeName = ref('first');
const tabNodePaths = ref(new Map());
// 加载树结构数据
const loadTreeData = (data) => {
  loading.value = true;
  getFastenerTree({
    sheetName: '',
    plateName: '',
    fastenerGrade: '',
    unit: data
  }).then((res) => {
    const result = res && res?.data;
    treeData.value = result;
    loading.value = false;
    nextTick(() => {
      if (data === 'imperial') {
        restoreTreePath('first');
      } else {
        restoreTreePath('second');
      }
    });
  });
};
// 监听树结构查询条件
watchEffect(
  () => {
    materialTree.value?.filter(queryName.value);
    // 添加强制刷新逻辑
    nextTick(() => {
      materialTree.value?.updateKeyChildren(
        'highlight',
        {} // 触发节点重新渲染
      );
    });
  },
  {
    flush: 'post'
  }
);

// 过滤树节点
const filterNode = (value, data, node) => {
  if (!value) return true;

  // 当前节点匹配
  const isCurrentMatch = data.nodeName.indexOf(value) !== -1;

  // 父节点匹配（需排除根节点）
  const isParentMatch = node.parent && node.parent.data.nodeName && node.parent.data.nodeName.indexOf(value) !== -1;
  const isGrandParentMatch = node.parent.parent && node.parent.parent.data.nodeName && node.parent.parent.data.nodeName.indexOf(value) !== -1;

  // 逻辑：显示匹配节点及其直接子节点
  return isCurrentMatch || isParentMatch || isGrandParentMatch;
};

// 清除查询条件
const clearQuery = () => {};
// tree选择事件

const customTreeClick = (data, node, component) => {
  // 判断当前点击节点的层级
  if (getNodeLevel(node) === 4) {
    currentNodeKey.value = data._id;
    treeSelect(data, node, component);
  } else {
    materialTree.value?.setCurrentKey(currentNodeKey.value);
  }
};
// 获取节点层级
const getNodeLevel = (node) => {
  let level = 0;
  let currentNode = node;
  while (currentNode !== null) {
    level++;
    currentNode = currentNode.parent;
  }
  return level;
};

const treeSelect = (selected, node) => {
  console.log('selected, node', selected, node);
  const path = [];
  let currentNode = node;
  // 向上遍历父节点构造路径
  while (currentNode && currentNode.data.nodeName) {
    path.unshift(currentNode.data.nodeName);
    currentNode = currentNode.parent;
  }
  // 关联到当前tab
  tabNodePaths.value.set(activeName.value, path);
  console.log('tabNodePaths.value', tabNodePaths.value);
  if (selected && selected._id) {
    selectTreeNodeId.value = selected._id;
    fastenerGrade.value = selected.fastenerGrade;
  } else {
    selectTreeNodeId.value = '';
    fastenerGrade.value = '';
  }
};
// 修改后的还原逻辑
const restoreTreePath = async (tabKey) => {
  const pathNames = tabNodePaths.value.get(tabKey) || [];
  if (tabKey === 'first') {
    tabNodePaths.value.set('second', pathNames);
    tabNodePaths.value.delete('first');
  } else {
    tabNodePaths.value.set('first', pathNames);
    tabNodePaths.value.delete('second');
  }
  console.log('pathNames', pathNames);
  if (!pathNames.length || !materialTree.value) return;

  // 从根节点的子节点开始遍历
  let currentNodes = materialTree.value.root.data;
  console.log('currentNodes', currentNodes);
  let targetNode = null;
  // 逐层遍历路径
  for (const name of pathNames) {
    const foundNode = currentNodes.find((n) => n.nodeName === name);
    if (!foundNode) break;
    // 进入下一层级
    currentNodes = foundNode.children;
    targetNode = foundNode;
  }
  // 选中最终找到的节点
  if (targetNode) {
    materialTree.value.setCurrentKey(targetNode._id);
    selectTreeNodeId.value = targetNode._id;
  }
};

// tab切换事件
const handleClick = () => {
  if (activeName.value === 'first') {
    activeName.value = 'second';
    loadTreeData('imperial');
  } else {
    activeName.value = 'first';
    loadTreeData('metric');
  }
};
const highlightLabel = (labelText) => {
  if (!queryName.value) return labelText;
  const reg = new RegExp(escapeRegExp(queryName.value), 'gi');
  return labelText.replace(reg, '<span style="color: red">$&</span>');
};

// 添加正则表达式转义函数
const escapeRegExp = (string) => {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};

// 拖拽窗口
let startX = 0;
let startWidth = 0;

const startResize = (event) => {
  startX = event.clientX;
  startWidth = leftWidth.value;
  window.addEventListener('mousemove', onResize);
  window.addEventListener('mouseup', stopResize);
};

const onResize = (event) => {
  const dx = event.clientX - startX;
  const newWidth = startWidth + (dx / window.innerWidth) * 100;
  leftWidth.value = Math.max(10, Math.min(90, newWidth)); // 限制宽度在10%到90%之间
};

const stopResize = () => {
  window.removeEventListener('mousemove', onResize);
  window.removeEventListener('mouseup', stopResize);
};

onUnmounted(() => {
  window.removeEventListener('mousemove', onResize);
  window.removeEventListener('mouseup', stopResize);
});

const handleUpload = () => {
  importVisible.value = true;
};
const handleImportEvent = (data) => {
  if (data?.type === 'refresh') {
    importVisible.value = false;
    getListData();
  } else {
    importVisible.value = false;
  }
};
// 初始化
onMounted(() => {
  loadTreeData('metric');
});
</script>
<style lang="scss" scoped>
// .card {
//   height: calc(100vh - 95px);
//   overflow: auto;
//   margin: 5px;
// }
.mainStyle {
  height: calc(100vh - 158px);
  display: flex;
}
.treeDiv {
  height: 100%;
  overflow: auto;
  margin-left: 5px;
  margin-right: 5px;
  border-right: 1px solid #dddddd7a;
}
.resizer {
  position: relative;
  width: 0.3%;
  background-color: #d9d9d9;
  cursor: ew-resize;
  border-radius: 5px;
}
.rightDiv {
  height: 100%;
  flex: 1;
  overflow: auto;
  margin-left: 5px;
  margin-right: 5px;
}
:deep(.el-tree-node__label) {
  font-size: 12px;
  color: #606266;
}
:deep(.el-tree-node__content span span[style*='red']) {
  color: red !important;
}
</style>
